import io
from finder import Finder
from openpyxl import load_workbook
import tools
import pytesseract
from PIL import Image


class ExcelFinder(Finder):
    @staticmethod
    def file_suffixes():
        return [".xlsx"]
    
    def search_file(self, file_path, search_content):
        all_text_of_excel = ""
        try:
            work_book = load_workbook(file_path)
        except Exception as e:
            print(f"Error: Excel处理中发生了异常{file_path}")
            return

        all_sheets = work_book.worksheets
        for sheet in all_sheets:
            for row in sheet.iter_rows(values_only=True):
                for cell in row:
                    if isinstance(cell, str):
                        print(f"Processing cell {cell}")
                        all_text_of_excel += cell

        for img in work_book.active._images:
            try:
                image_text = pytesseract.image_to_string(Image.open(io.BytesIO(img._data())),"chi_sim")
                # print(f"{file_path}'s image text is {image_text}")
                all_text_of_excel += image_text
            except Exception as  e:
                print("Error: Excel中图片处理遇到了错误")

        work_book.close()
        with tools.lock:
            tools.global_store[file_path] = all_text_of_excel
        pass

        if search_content in Finder.process_text_if_need(all_text_of_excel.lower()):
            print(f"Found {search_content} in {file_path}")
